// 全局变量
let currentTab = 'dashboard';
let systemData = {};
let websocket = null;
let reconnectAttempts = 0;
const maxReconnectAttempts = 5;

// API基础URL
const API_BASE = '/api/v1';
const WS_BASE = 'ws://localhost:7880/api/v1/ws';

// 初始化
document.addEventListener('DOMContentLoaded', function() {
    setupEventListeners();
    initializeApp();
});

// 设置事件监听器
function setupEventListeners() {
    console.log('🔧 设置事件监听器...');
    
    // Tab切换事件监听器
    document.querySelectorAll('.nav-tab').forEach(tab => {
        tab.addEventListener('click', function() {
            const tabName = this.getAttribute('data-tab');
            console.log('🖱️ 点击标签页:', tabName);
            switchTab(tabName);
        });
    });
    
    // 刷新按钮事件监听器
    const refreshAllBtn = document.getElementById('refreshAllBtn');
    if (refreshAllBtn) {
        refreshAllBtn.addEventListener('click', refreshAll);
    }
    
    // 健康检查按钮
    const checkHealthBtn = document.getElementById('checkHealthBtn');
    if (checkHealthBtn) {
        checkHealthBtn.addEventListener('click', checkSystemHealth);
    }
    
    // 服务状态刷新按钮
    const refreshServiceBtn = document.getElementById('refreshServiceBtn');
    if (refreshServiceBtn) {
        refreshServiceBtn.addEventListener('click', loadServiceStatus);
    }
    
    // 统计信息刷新按钮
    const refreshStatsBtn = document.getElementById('refreshStatsBtn');
    if (refreshStatsBtn) {
        refreshStatsBtn.addEventListener('click', loadStatistics);
    }
    
    // 活动刷新按钮
    const refreshActivityBtn = document.getElementById('refreshActivityBtn');
    if (refreshActivityBtn) {
        refreshActivityBtn.addEventListener('click', loadRecentActivity);
    }

    const refreshMetricsBtn = document.getElementById('refreshMetricsBtn');
    if (refreshMetricsBtn) {
        refreshMetricsBtn.addEventListener('click', loadSystemMetrics);
    }

    const refreshWebSocketBtn = document.getElementById('refreshWebSocketBtn');
    if (refreshWebSocketBtn) {
        refreshWebSocketBtn.addEventListener('click', loadWebSocketStatus);
    }

    // 批量操作下拉菜单
    const batchActionsBtn = document.getElementById('batchActionsBtn');
    const batchActionsMenu = document.getElementById('batchActionsMenu');
    if (batchActionsBtn && batchActionsMenu) {
        batchActionsBtn.addEventListener('click', function(e) {
            e.stopPropagation();
            batchActionsMenu.classList.toggle('show');
        });

        // 点击其他地方关闭下拉菜单
        document.addEventListener('click', function() {
            batchActionsMenu.classList.remove('show');
        });
    }
    
    // 模型管理按钮
    const createModelBtn = document.getElementById('createModelBtn');
    if (createModelBtn) {
        createModelBtn.addEventListener('click', showCreateModelModal);
    }
    
    const refreshModelsBtn = document.getElementById('refreshModelsBtn');
    if (refreshModelsBtn) {
        refreshModelsBtn.addEventListener('click', loadModels);
    }
    
    const triggerDiscoveryBtn = document.getElementById('triggerDiscoveryBtn');
    if (triggerDiscoveryBtn) {
        triggerDiscoveryBtn.addEventListener('click', triggerModelDiscovery);
    }
    
    // 订阅管理按钮
    const createSubscriptionBtn = document.getElementById('createSubscriptionBtn');
    if (createSubscriptionBtn) {
        createSubscriptionBtn.addEventListener('click', showCreateSubscriptionModal);
    }
    
    const refreshSubscriptionsBtn = document.getElementById('refreshSubscriptionsBtn');
    if (refreshSubscriptionsBtn) {
        refreshSubscriptionsBtn.addEventListener('click', loadSubscriptions);
    }
    
    // 服务器管理按钮
    const createServerBtn = document.getElementById('createServerBtn');
    if (createServerBtn) {
        createServerBtn.addEventListener('click', showCreateServerModal);
    }
    
    const refreshServersBtn = document.getElementById('refreshServersBtn');
    if (refreshServersBtn) {
        refreshServersBtn.addEventListener('click', loadServers);
    }
    
    // 通知管理按钮
    const sendNotificationBtn = document.getElementById('sendNotificationBtn');
    if (sendNotificationBtn) {
        sendNotificationBtn.addEventListener('click', showSendNotificationModal);
    }
    
    const refreshNotificationsBtn = document.getElementById('refreshNotificationsBtn');
    if (refreshNotificationsBtn) {
        refreshNotificationsBtn.addEventListener('click', loadNotifications);
    }
    
    // 系统设置按钮
    const saveSettingsBtn = document.getElementById('saveSettingsBtn');
    if (saveSettingsBtn) {
        saveSettingsBtn.addEventListener('click', saveSystemSettings);
    }
    
    const reloadSettingsBtn = document.getElementById('reloadSettingsBtn');
    if (reloadSettingsBtn) {
        reloadSettingsBtn.addEventListener('click', loadSystemSettings);
    }
    
    // 模型分发按钮
    const dispatchModelBtn = document.getElementById('dispatchModelBtn');
    if (dispatchModelBtn) {
        dispatchModelBtn.addEventListener('click', showDispatchModelForm);
    }
    
    const refreshDispatchBtn = document.getElementById('refreshDispatchBtn');
    if (refreshDispatchBtn) {
        refreshDispatchBtn.addEventListener('click', loadDispatchStatus);
    }
    
    const refreshClientsBtn = document.getElementById('refreshClientsBtn');
    if (refreshClientsBtn) {
        refreshClientsBtn.addEventListener('click', loadAvailableClients);
    }
    
    const refreshDispatchStatusBtn = document.getElementById('refreshDispatchStatusBtn');
    if (refreshDispatchStatusBtn) {
        refreshDispatchStatusBtn.addEventListener('click', loadDispatchStatus);
    }
    
    const refreshAvailableClientsBtn = document.getElementById('refreshAvailableClientsBtn');
    if (refreshAvailableClientsBtn) {
        refreshAvailableClientsBtn.addEventListener('click', loadAvailableClients);
    }
    
    // 分发表单提交
    const dispatchForm = document.getElementById('dispatchForm');
    if (dispatchForm) {
        dispatchForm.addEventListener('submit', handleDispatchSubmit);
    }
    
    // 模态框事件监听器
    setupModalEventListeners();
    
    console.log('✅ 事件监听器设置完成');
}

// 设置模态框事件监听器
function setupModalEventListeners() {
    // 模态框背景点击关闭
    document.querySelectorAll('[data-modal]').forEach(modal => {
        modal.addEventListener('click', function(e) {
            if (e.target === this) {
                const modalId = this.getAttribute('data-modal');
                hideModal(modalId);
            }
        });
    });
    
    // 模态框关闭按钮
    document.querySelectorAll('[data-modal-close]').forEach(closeBtn => {
        closeBtn.addEventListener('click', function() {
            const modalId = this.getAttribute('data-modal-close');
            hideModal(modalId);
        });
    });
}

// 应用初始化
async function initializeApp() {
    console.log('🚀 初始化系统管理界面...');

    // 测试switchTab函数是否可用
    console.log('🧪 测试switchTab函数:', typeof switchTab);

    // 检查系统状态
    await checkSystemHealth();

    // 加载仪表板数据
    await loadDashboardData();

    // 初始化模型分发页面的客户端列表
    await initializeModelDispatch();

    // 初始化WebSocket连接
    initializeWebSocket();

    console.log('✅ 系统管理界面初始化完成');
}

// 初始化模型分发功能
async function initializeModelDispatch() {
    console.log('🚀 初始化模型分发功能...');
    try {
        // 预加载可用客户端列表
        await loadAvailableClients();
    } catch (error) {
        console.error('❌ 初始化模型分发功能失败:', error);
    }
}

// 标签页切换
function switchTab(tabName) {
    console.log('🔄 切换标签页到:', tabName);
    
    try {
    // 隐藏所有标签页
    document.querySelectorAll('.tab-content').forEach(tab => {
        tab.classList.remove('active');
    });
    
    // 移除所有标签按钮的激活状态
    document.querySelectorAll('.nav-tab').forEach(btn => {
        btn.classList.remove('active');
    });
    
    // 显示目标标签页
    const targetTab = document.getElementById(`${tabName}-tab`);
        console.log('🎯 目标标签页:', targetTab);
    if (targetTab) {
        targetTab.classList.add('active');
            console.log('✅ 标签页已激活');
        } else {
            console.error('❌ 未找到目标标签页:', `${tabName}-tab`);
            return;
    }
    
    // 激活对应的标签按钮
        const targetBtn = document.querySelector(`[data-tab="${tabName}"]`);
        console.log('🎯 目标按钮:', targetBtn);
    if (targetBtn) {
        targetBtn.classList.add('active');
            console.log('✅ 按钮已激活');
        } else {
            console.error('❌ 未找到目标按钮');
    }
    
    currentTab = tabName;
    
        // 延迟加载数据，避免阻塞UI
        setTimeout(async () => {
            try {
    switch(tabName) {
        case 'dashboard':
                        await loadDashboardData();
                        break;
                    case 'models':
                        await loadModels();
            break;
        case 'subscriptions':
                        await loadSubscriptions();
            break;
        case 'servers':
                        await loadServers();
            break;
        case 'clients':
            await loadClients();
            break;
        case 'model-status':
            await loadModelStatusStats();
            await loadModelStatus();
            break;
        case 'model-dispatch':
            await loadDispatchStatus();
            await loadAvailableClients();
            break;
        case 'notifications':
                        await loadNotifications();
            break;
        case 'system':
                        await loadSystemData();
            break;
    }
            } catch (error) {
                console.error('❌ 加载标签页数据失败:', error);
            }
        }, 100);
        
    } catch (error) {
        console.error('❌ 切换标签页失败:', error);
    }
}

// 检查系统健康状态
async function checkSystemHealth() {
    const statusIndicator = document.getElementById('systemStatus');
    const healthStatus = document.getElementById('healthStatus');
    
    try {
        const response = await fetch(`${API_BASE}/health/status`);
        const data = await response.json();
        
        if (data.status === 'healthy') {
            updateStatusIndicator(statusIndicator, 'healthy', '系统正常');
            if (healthStatus) {
                healthStatus.innerHTML = renderHealthStatus(data);
            }
        } else {
            updateStatusIndicator(statusIndicator, 'error', '系统异常');
            if (healthStatus) {
                healthStatus.innerHTML = `<div class="error">系统状态异常: ${data.message || '未知错误'}</div>`;
            }
        }
    } catch (error) {
        console.error('检查系统健康状态失败:', error);
        updateStatusIndicator(statusIndicator, 'error', '连接失败');
        if (healthStatus) {
            healthStatus.innerHTML = `<div class="error">无法连接到服务器</div>`;
        }
    }
}

// 更新状态指示器
function updateStatusIndicator(element, status, text) {
    const dot = element.querySelector('.status-dot');
    const textEl = element.querySelector('.status-text');
    
    // 移除所有状态类
    dot.classList.remove('healthy', 'error');
    
    // 添加新状态类
    if (status !== 'checking') {
        dot.classList.add(status);
    }
    
    textEl.textContent = text;
}

// 渲染健康状态
function renderHealthStatus(data) {
    return `
        <div class="health-grid">
            <div class="health-item">
                <span class="health-label">系统状态:</span>
                <span class="status-badge ${data.status}">${data.status}</span>
            </div>
            <div class="health-item">
                <span class="health-label">运行时间:</span>
                <span class="health-value">${data.uptime || 'N/A'}</span>
            </div>
            <div class="health-item">
                <span class="health-label">版本:</span>
                <span class="health-value">${data.version || 'N/A'}</span>
            </div>
            <div class="health-item">
                <span class="health-label">最后检查:</span>
                <span class="health-value">${new Date().toLocaleString('zh-CN')}</span>
            </div>
        </div>
    `;
}

// 加载仪表板数据
async function loadDashboardData() {
    await Promise.all([
        loadServiceStatus(),
        loadStatistics(),
        loadSystemMetrics(),
        loadWebSocketStatus()
    ]);
}

// 加载系统设置页面数据
async function loadSystemData() {
    await Promise.all([
        loadHealthStatus(),
        loadRecentActivity(),
        loadSystemSettings()
    ]);
}

// 加载健康状态
async function loadHealthStatus() {
    try {
        const response = await fetch(`${API_BASE}/health`);
        const data = await response.json();
        
        // 更新健康状态显示
        const healthStatus = document.getElementById('healthStatus');
        if (healthStatus) {
            healthStatus.textContent = data.status || 'unknown';
            healthStatus.className = `status-badge ${data.status === 'healthy' ? 'active' : 'inactive'}`;
        }
    } catch (error) {
        console.error('加载健康状态失败:', error);
    }
}

// 加载服务状态
async function loadServiceStatus() {
    const container = document.getElementById('serviceStatus');
    if (!container) return;
    
    try {
        const response = await fetch(`${API_BASE}/admin/services/status`);
        const data = await response.json();
        
        container.innerHTML = renderServiceStatus(data);
    } catch (error) {
        console.error('加载服务状态失败:', error);
        container.innerHTML = '<div class="error">加载服务状态失败</div>';
    }
}

// 渲染服务状态
function renderServiceStatus(data) {
    const services = data.services || {};
    
    return `
        <div class="service-grid">
            ${Object.entries(services).map(([name, status]) => `
                <div class="service-item">
                    <div class="service-name">${name}</div>
                    <div class="status-badge ${status.status}">${status.status}</div>
                    ${status.message ? `<div class="service-message">${status.message}</div>` : ''}
                </div>
            `).join('')}
        </div>
    `;
}

// 加载统计信息
async function loadStatistics() {
    const container = document.getElementById('statisticsInfo');
    if (!container) return;
    
    try {
        const response = await fetch(`${API_BASE}/admin/statistics`);
        const data = await response.json();
        
        container.innerHTML = renderStatistics(data);
    } catch (error) {
        console.error('加载统计信息失败:', error);
        container.innerHTML = '<div class="error">加载统计信息失败</div>';
    }
}

// 渲染统计信息
function renderStatistics(data) {
    return `
        <div class="stats-grid">
            <div class="stat-item">
                <div class="stat-number">${data.total_models || 0}</div>
                <div class="stat-label">总模型数</div>
            </div>
            <div class="stat-item">
                <div class="stat-number">${data.active_subscriptions || 0}</div>
                <div class="stat-label">活跃订阅</div>
            </div>
            <div class="stat-item">
                <div class="stat-number">${data.total_servers || 0}</div>
                <div class="stat-label">服务器数</div>
            </div>
            <div class="stat-item">
                <div class="stat-number">${data.notifications_sent || 0}</div>
                <div class="stat-label">通知发送</div>
            </div>
        </div>
    `;
}

// 加载最近活动
async function loadRecentActivity() {
    const container = document.getElementById('recentActivity');
    if (!container) return;
    
    try {
        const response = await fetch(`${API_BASE}/admin/activity`);
        const data = await response.json();
        
        container.innerHTML = renderRecentActivity(data.activities || []);
    } catch (error) {
        console.error('加载最近活动失败:', error);
        container.innerHTML = '<div class="error">加载最近活动失败</div>';
    }
}

// 渲染最近活动
function renderRecentActivity(activities) {
    if (activities.length === 0) {
        return '<div class="no-data">暂无最近活动</div>';
    }

    return `
        <div class="activity-list">
            ${activities.slice(0, 10).map(activity => `
                <div class="activity-item">
                    <div class="activity-time">${new Date(activity.timestamp).toLocaleString('zh-CN')}</div>
                    <div class="activity-content">${activity.message}</div>
                    <div class="activity-type">${activity.type}</div>
                </div>
            `).join('')}
        </div>
    `;
}

// 加载系统指标
async function loadSystemMetrics() {
    const container = document.getElementById('systemMetrics');
    if (!container) return;

    try {
        const response = await fetch(`${API_BASE}/admin/performance/metrics`);
        const data = await response.json();

        if (data.success) {
            container.innerHTML = renderSystemMetrics(data.data || {});
        } else {
            container.innerHTML = '<div class="error">加载系统指标失败</div>';
        }
    } catch (error) {
        console.error('加载系统指标失败:', error);
        container.innerHTML = '<div class="error">加载系统指标失败</div>';
    }
}

// 渲染系统指标
function renderSystemMetrics(metrics) {
    const system = metrics.system || {};
    const api = metrics.api || {};

    return `
        <div class="metrics-grid">
            <div class="metric-card">
                <div class="metric-label">CPU使用率</div>
                <div class="metric-value">${system.cpu_percent || 0}%</div>
                <div class="metric-bar">
                    <div class="metric-fill" style="width: ${system.cpu_percent || 0}%"></div>
                </div>
            </div>
            <div class="metric-card">
                <div class="metric-label">内存使用率</div>
                <div class="metric-value">${system.memory_percent || 0}%</div>
                <div class="metric-bar">
                    <div class="metric-fill" style="width: ${system.memory_percent || 0}%"></div>
                </div>
            </div>
            <div class="metric-card">
                <div class="metric-label">磁盘使用率</div>
                <div class="metric-value">${system.disk_percent || 0}%</div>
                <div class="metric-bar">
                    <div class="metric-fill" style="width: ${system.disk_percent || 0}%"></div>
                </div>
            </div>
            <div class="metric-card">
                <div class="metric-label">API响应时间</div>
                <div class="metric-value">${api.avg_response_time || 0}ms</div>
                <div class="metric-trend ${api.response_time_trend || 'stable'}">${api.response_time_trend || 'stable'}</div>
            </div>
        </div>
    `;
}

// 加载WebSocket状态
async function loadWebSocketStatus() {
    const container = document.getElementById('websocketStatus');
    if (!container) return;

    try {
        const response = await fetch(`${API_BASE}/admin/websocket/status`);
        const data = await response.json();

        if (data.success) {
            container.innerHTML = renderWebSocketStatus(data.data || {});
        } else {
            container.innerHTML = '<div class="error">加载WebSocket状态失败</div>';
        }
    } catch (error) {
        console.error('加载WebSocket状态失败:', error);
        container.innerHTML = '<div class="error">加载WebSocket状态失败</div>';
    }
}

// 渲染WebSocket状态
function renderWebSocketStatus(status) {
    const connections = status.connections || 0;
    const messages = status.total_messages || 0;
    const clients = status.active_clients || [];

    return `
        <div class="websocket-status">
            <div class="status-summary">
                <div class="status-item">
                    <div class="status-label">活跃连接</div>
                    <div class="status-value">${connections}</div>
                </div>
                <div class="status-item">
                    <div class="status-label">总消息数</div>
                    <div class="status-value">${messages}</div>
                </div>
            </div>
            <div class="client-list">
                <div class="client-header">活跃客户端</div>
                ${clients.length > 0 ? clients.map(client => `
                    <div class="client-item">
                        <div class="client-id">${client.client_id}</div>
                        <div class="client-connected">${new Date(client.connected_at * 1000).toLocaleString('zh-CN')}</div>
                    </div>
                `).join('') : '<div class="no-clients">暂无活跃客户端</div>'}
            </div>
        </div>
    `;
}

// 全部刷新
async function refreshAll() {
    const btn = document.getElementById('refreshAllBtn');
    if (!btn) return;
    
    const originalText = btn.innerHTML;
    
    btn.disabled = true;
    btn.innerHTML = '🔄 刷新中...';
    
    try {
        await checkSystemHealth();
        
        if (currentTab === 'dashboard') {
            await loadDashboardData();
        } else {
            // 根据当前标签页刷新对应数据
            switch(currentTab) {
                case 'subscriptions':
                    await loadSubscriptions();
                    break;
                case 'servers':
                    await loadServers();
                    break;
                case 'notifications':
                    await loadNotifications();
                    break;
                case 'system':
                    await loadSystemData();
                    break;
            }
        }
        
        showNotification('刷新成功', 'success');
    } catch (error) {
        console.error('刷新失败:', error);
        showNotification('刷新失败', 'error');
    } finally {
        btn.disabled = false;
        btn.innerHTML = originalText;
    }
}

// 显示通知
function showNotification(message, type = 'info') {
    const container = document.getElementById('notificationContainer');
    const notification = document.createElement('div');
    notification.className = `notification notification-${type}`;
    notification.innerHTML = `
        <span>${message}</span>
        <button onclick="this.parentElement.remove()">×</button>
    `;
    
    container.appendChild(notification);
    
    // 3秒后自动移除
    setTimeout(() => {
        if (notification.parentElement) {
            notification.remove();
        }
    }, 3000);
}

// ==================== 模态框组件 ====================

// 显示模态框
function showModal(modalId, title = '', content = '') {
    const modal = document.getElementById(modalId);
    if (!modal) {
        console.error(`模态框 ${modalId} 不存在`);
        return;
    }
    
    // 设置标题和内容
    const titleEl = modal.querySelector('.modal-title');
    const contentEl = modal.querySelector('.modal-content');
    
    if (titleEl && title) titleEl.textContent = title;
    if (contentEl && content) contentEl.innerHTML = content;
    
    // 显示模态框
    modal.style.display = 'flex';
    document.body.style.overflow = 'hidden';
    
    // 添加动画效果
    setTimeout(() => {
        modal.classList.add('show');
    }, 10);
}

// 隐藏模态框
function hideModal(modalId) {
    const modal = document.getElementById(modalId);
    if (!modal) return;
    
    modal.classList.remove('show');
    setTimeout(() => {
        modal.style.display = 'none';
        document.body.style.overflow = 'auto';
    }, 300);
}

// 点击模态框背景关闭
function closeModalOnBackground(event) {
    if (event.target.classList.contains('modal')) {
        const modalId = event.target.id;
        hideModal(modalId);
    }
}

// ==================== 订阅管理功能 ====================

// 加载订阅列表
async function loadSubscriptions() {
    const container = document.getElementById('subscriptionsList');
    if (!container) return;
    
    try {
        container.innerHTML = '<div class="loading">加载订阅列表...</div>';
        
        const response = await fetch(`${API_BASE}/subscriptions`);
        const data = await response.json();
        
        if (data.success) {
            container.innerHTML = renderSubscriptionsTable(data.data || []);
        } else {
            container.innerHTML = '<div class="error">加载订阅列表失败</div>';
        }
    } catch (error) {
        console.error('加载订阅列表失败:', error);
        container.innerHTML = '<div class="error">加载订阅列表失败</div>';
    }
}

// 渲染订阅表格
function renderSubscriptionsTable(subscriptions) {
    if (subscriptions.length === 0) {
        return `
            <div class="no-data">
                <p>暂无订阅记录</p>
                <button class="btn btn-primary" onclick="showCreateSubscriptionModal()">创建订阅</button>
            </div>
        `;
    }
    
    return `
        <div class="table-header">
            <h3>订阅列表</h3>
            <button class="btn btn-primary" onclick="showCreateSubscriptionModal()">创建订阅</button>
        </div>
        <div class="table-container">
            <table class="data-table">
                <thead>
                    <tr>
                        <th width="40">
                            <input type="checkbox" id="selectAllCheckbox" onchange="toggleSelectAll(this)">
                        </th>
                        <th>ID</th>
                        <th>客户端</th>
                        <th>模型名称</th>
                        <th>服务器</th>
                        <th>状态</th>
                        <th>创建时间</th>
                        <th>最后检查</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody>
                    ${subscriptions.map(sub => `
                        <tr>
                            <td>
                                <input type="checkbox" class="subscription-checkbox" value="${sub.id}"
                                       onchange="toggleSubscriptionSelection('${sub.id}', this)">
                            </td>
                            <td>${sub.id.substring(0, 8)}...</td>
                            <td>
                                <div class="client-info">
                                    <div class="client-name">${sub.client_name || sub.client_id}</div>
                                    <div class="client-id">${sub.client_id}</div>
                                </div>
                            </td>
                            <td>${sub.model_name}</td>
                            <td>${sub.server_id}</td>
                            <td><span class="status-badge ${sub.status}">${sub.status}</span></td>
                            <td>${new Date(sub.created_at * 1000).toLocaleString('zh-CN')}</td>
                            <td>${sub.last_checked ? new Date(sub.last_checked * 1000).toLocaleString('zh-CN') : 'N/A'}</td>
                            <td>
                                <button class="btn btn-sm btn-secondary" onclick="editSubscription('${sub.id}')">编辑</button>
                                <button class="btn btn-sm btn-danger" onclick="deleteSubscription('${sub.id}')">删除</button>
                                <button class="btn btn-sm btn-info" onclick="checkSubscription('${sub.id}')">检查</button>
                            </td>
                        </tr>
                    `).join('')}
                </tbody>
            </table>
        </div>
    `;
}

// 显示创建订阅模态框
function showCreateSubscriptionModal() {
    const content = `
        <form id="createSubscriptionForm" onsubmit="createSubscription(event)">
            <div class="form-group">
                <label for="modelName">模型名称 *</label>
                <input type="text" id="modelName" name="model_name" required>
            </div>
            <div class="form-group">
                <label for="serverUrl">服务器URL *</label>
                <input type="url" id="serverUrl" name="server_url" required>
            </div>
            <div class="form-group">
                <label for="checkInterval">检查间隔(秒)</label>
                <input type="number" id="checkInterval" name="check_interval" value="60" min="10">
            </div>
            <div class="form-group">
                <label for="timeout">超时时间(秒)</label>
                <input type="number" id="timeout" name="timeout" value="30" min="5">
            </div>
            <div class="form-actions">
                <button type="button" class="btn btn-secondary" onclick="hideModal('createSubscriptionModal')">取消</button>
                <button type="submit" class="btn btn-primary">创建</button>
            </div>
        </form>
    `;
    
    showModal('createSubscriptionModal', '创建订阅', content);
}

// 创建订阅
async function createSubscription(event) {
    event.preventDefault();
    
    const form = event.target;
    const formData = new FormData(form);
    const data = Object.fromEntries(formData.entries());
    
    try {
        const response = await fetch(`${API_BASE}/subscriptions`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(data)
        });
        
        const result = await response.json();
        
        if (result.success) {
            showNotification('订阅创建成功', 'success');
            hideModal('createSubscriptionModal');
            loadSubscriptions();
        } else {
            showNotification(`创建失败: ${result.message}`, 'error');
        }
    } catch (error) {
        console.error('创建订阅失败:', error);
        showNotification('创建订阅失败', 'error');
    }
}

// 编辑订阅
async function editSubscription(subscriptionId) {
    try {
        const response = await fetch(`${API_BASE}/subscriptions/${subscriptionId}`);
        const result = await response.json();
        
        if (result.success) {
            const subscription = result.data;
            const content = `
                <form id="editSubscriptionForm" onsubmit="updateSubscription(event, ${subscriptionId})">
                    <div class="form-group">
                        <label for="editModelName">模型名称 *</label>
                        <input type="text" id="editModelName" name="model_name" value="${subscription.model_name}" required>
                    </div>
                    <div class="form-group">
                        <label for="editServerUrl">服务器URL *</label>
                        <input type="url" id="editServerUrl" name="server_url" value="${subscription.server_url}" required>
                    </div>
                    <div class="form-group">
                        <label for="editCheckInterval">检查间隔(秒)</label>
                        <input type="number" id="editCheckInterval" name="check_interval" value="${subscription.check_interval || 60}" min="10">
                    </div>
                    <div class="form-group">
                        <label for="editTimeout">超时时间(秒)</label>
                        <input type="number" id="editTimeout" name="timeout" value="${subscription.timeout || 30}" min="5">
                    </div>
                    <div class="form-actions">
                        <button type="button" class="btn btn-secondary" onclick="hideModal('editSubscriptionModal')">取消</button>
                        <button type="submit" class="btn btn-primary">更新</button>
                    </div>
                </form>
            `;
            
            showModal('editSubscriptionModal', '编辑订阅', content);
        } else {
            showNotification('获取订阅信息失败', 'error');
        }
    } catch (error) {
        console.error('获取订阅信息失败:', error);
        showNotification('获取订阅信息失败', 'error');
    }
}

// 更新订阅
async function updateSubscription(event, subscriptionId) {
    event.preventDefault();
    
    const form = event.target;
    const formData = new FormData(form);
    const data = Object.fromEntries(formData.entries());
    
    try {
        const response = await fetch(`${API_BASE}/subscriptions/${subscriptionId}`, {
            method: 'PUT',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(data)
        });
        
        const result = await response.json();
        
        if (result.success) {
            showNotification('订阅更新成功', 'success');
            hideModal('editSubscriptionModal');
            loadSubscriptions();
        } else {
            showNotification(`更新失败: ${result.message}`, 'error');
        }
    } catch (error) {
        console.error('更新订阅失败:', error);
        showNotification('更新订阅失败', 'error');
    }
}

// 删除订阅
async function deleteSubscription(subscriptionId) {
    if (!confirm('确定要删除这个订阅吗？')) {
        return;
    }

    try {
        const response = await fetch(`${API_BASE}/subscriptions/${subscriptionId}`, {
            method: 'DELETE'
        });

        const result = await response.json();

        if (result.success) {
            showNotification('订阅删除成功', 'success');
            loadSubscriptions();
        } else {
            showNotification(`删除失败: ${result.message}`, 'error');
        }
    } catch (error) {
        console.error('删除订阅失败:', error);
        showNotification('删除订阅失败', 'error');
    }
}

// ==================== 批量操作功能 ====================

let selectedSubscriptions = new Set();

// 选择/取消选择订阅
function toggleSubscriptionSelection(subscriptionId, checkbox) {
    if (checkbox.checked) {
        selectedSubscriptions.add(subscriptionId);
    } else {
        selectedSubscriptions.delete(subscriptionId);
    }
    updateSelectionUI();
}

// 全选订阅
function selectAllSubscriptions() {
    const checkboxes = document.querySelectorAll('.subscription-checkbox');
    checkboxes.forEach(checkbox => {
        checkbox.checked = true;
        selectedSubscriptions.add(checkbox.value);
    });
    updateSelectionUI();
}

// 清空选择
function clearSelection() {
    const checkboxes = document.querySelectorAll('.subscription-checkbox');
    checkboxes.forEach(checkbox => {
        checkbox.checked = false;
    });
    selectedSubscriptions.clear();
    updateSelectionUI();
}

// 更新选择UI
function updateSelectionUI() {
    const selectedCount = selectedSubscriptions.size;
    const countElement = document.getElementById('selectedCount');
    const selectionElement = document.getElementById('batchSelection');

    if (countElement) {
        countElement.textContent = selectedCount;
    }

    if (selectionElement) {
        selectionElement.style.display = selectedCount > 0 ? 'block' : 'none';
    }
}

// 批量暂停订阅
async function batchPauseSubscriptions() {
    if (selectedSubscriptions.size === 0) {
        showNotification('请先选择要暂停的订阅', 'warning');
        return;
    }

    if (!confirm(`确定要暂停 ${selectedSubscriptions.size} 个订阅吗？`)) {
        return;
    }

    try {
        const response = await fetch(`${API_BASE}/batch/subscriptions/pause`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                subscription_ids: Array.from(selectedSubscriptions)
            })
        });

        const result = await response.json();

        if (result.success) {
            showNotification(`成功暂停 ${result.data.success_count} 个订阅`, 'success');
            clearSelection();
            loadSubscriptions();
        } else {
            showNotification(`批量暂停失败: ${result.message}`, 'error');
        }
    } catch (error) {
        console.error('批量暂停订阅失败:', error);
        showNotification('批量暂停订阅失败', 'error');
    }
}

// 批量恢复订阅
async function batchResumeSubscriptions() {
    if (selectedSubscriptions.size === 0) {
        showNotification('请先选择要恢复的订阅', 'warning');
        return;
    }

    if (!confirm(`确定要恢复 ${selectedSubscriptions.size} 个订阅吗？`)) {
        return;
    }

    try {
        const response = await fetch(`${API_BASE}/batch/subscriptions/resume`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                subscription_ids: Array.from(selectedSubscriptions)
            })
        });

        const result = await response.json();

        if (result.success) {
            showNotification(`成功恢复 ${result.data.success_count} 个订阅`, 'success');
            clearSelection();
            loadSubscriptions();
        } else {
            showNotification(`批量恢复失败: ${result.message}`, 'error');
        }
    } catch (error) {
        console.error('批量恢复订阅失败:', error);
        showNotification('批量恢复订阅失败', 'error');
    }
}

// 批量删除订阅
async function batchDeleteSubscriptions() {
    if (selectedSubscriptions.size === 0) {
        showNotification('请先选择要删除的订阅', 'warning');
        return;
    }

    if (!confirm(`确定要删除 ${selectedSubscriptions.size} 个订阅吗？此操作不可恢复！`)) {
        return;
    }

    try {
        const response = await fetch(`${API_BASE}/batch/subscriptions/delete`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                subscription_ids: Array.from(selectedSubscriptions)
            })
        });

        const result = await response.json();

        if (result.success) {
            showNotification(`成功删除 ${result.data.success_count} 个订阅`, 'success');
            clearSelection();
            loadSubscriptions();
        } else {
            showNotification(`批量删除失败: ${result.message}`, 'error');
        }
    } catch (error) {
        console.error('批量删除订阅失败:', error);
        showNotification('批量删除订阅失败', 'error');
    }
}

// 批量检查订阅
async function batchCheckSubscriptions() {
    if (selectedSubscriptions.size === 0) {
        showNotification('请先选择要检查的订阅', 'warning');
        return;
    }

    try {
        const response = await fetch(`${API_BASE}/batch/subscriptions/check`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                subscription_ids: Array.from(selectedSubscriptions)
            })
        });

        const result = await response.json();

        if (result.success) {
            showNotification(`成功检查 ${result.data.success_count} 个订阅`, 'success');
            loadSubscriptions();
        } else {
            showNotification(`批量检查失败: ${result.message}`, 'error');
        }
    } catch (error) {
        console.error('批量检查订阅失败:', error);
        showNotification('批量检查订阅失败', 'error');
    }
}

// 全选/取消全选
function toggleSelectAll(checkbox) {
    const subscriptionCheckboxes = document.querySelectorAll('.subscription-checkbox');
    subscriptionCheckboxes.forEach(cb => {
        cb.checked = checkbox.checked;
        if (checkbox.checked) {
            selectedSubscriptions.add(cb.value);
        } else {
            selectedSubscriptions.delete(cb.value);
        }
    });
    updateSelectionUI();
}

// 检查单个订阅
async function checkSubscription(subscriptionId) {
    try {
        const response = await fetch(`${API_BASE}/subscriptions/${subscriptionId}/check`, {
            method: 'POST'
        });

        const result = await response.json();

        if (result.success) {
            showNotification('订阅检查成功', 'success');
            loadSubscriptions();
        } else {
            showNotification(`检查失败: ${result.message}`, 'error');
        }
    } catch (error) {
        console.error('检查订阅失败:', error);
        showNotification('检查订阅失败', 'error');
    }
}

// ==================== 服务器管理功能 ====================

// 加载服务器列表
async function loadServers() {
    const container = document.getElementById('serversList');
    if (!container) return;
    
    try {
        container.innerHTML = '<div class="loading">加载服务器列表...</div>';
        
        const response = await fetch(`${API_BASE}/servers`);
        const data = await response.json();
        
        if (data.success) {
            container.innerHTML = renderServersTable(data.data || []);
        } else {
            container.innerHTML = '<div class="error">加载服务器列表失败</div>';
        }
    } catch (error) {
        console.error('加载服务器列表失败:', error);
        container.innerHTML = '<div class="error">加载服务器列表失败</div>';
    }
}

// 渲染服务器表格
function renderServersTable(servers) {
    if (servers.length === 0) {
        return `
            <div class="no-data">
                <p>暂无服务器记录</p>
                <button class="btn btn-primary" onclick="showCreateServerModal()">添加服务器</button>
            </div>
        `;
    }
    
    return `
        <div class="table-header">
            <h3>服务器列表</h3>
            <button class="btn btn-primary" onclick="showCreateServerModal()">添加服务器</button>
        </div>
        <div class="table-container">
            <table class="data-table">
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>名称</th>
                        <th>URL</th>
                        <th>状态</th>
                        <th>最后检查</th>
                        <th>错误次数</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody>
                    ${servers.map(server => `
                        <tr>
                            <td>${server.id}</td>
                            <td>${server.name}</td>
                            <td>${server.url}</td>
                            <td><span class="status-badge ${server.status}">${server.status}</span></td>
                            <td>${server.last_checked ? new Date(server.last_checked).toLocaleString('zh-CN') : 'N/A'}</td>
                            <td>${server.consecutive_errors || 0}</td>
                            <td>
                                <button class="btn btn-sm btn-secondary" onclick="editServer(${server.id})">编辑</button>
                                <button class="btn btn-sm btn-danger" onclick="deleteServer(${server.id})">删除</button>
                                <button class="btn btn-sm btn-info" onclick="testServer(${server.id})">测试</button>
                            </td>
                        </tr>
                    `).join('')}
                </tbody>
            </table>
        </div>
    `;
}

// 显示创建服务器模态框
function showCreateServerModal() {
    const content = `
        <form id="createServerForm" onsubmit="createServer(event)">
            <div class="form-group">
                <label for="serverName">服务器名称 *</label>
                <input type="text" id="serverName" name="name" required>
            </div>
            <div class="form-group">
                <label for="serverUrl">服务器URL *</label>
                <input type="url" id="serverUrl" name="url" required>
            </div>
            <div class="form-group">
                <label for="serverDescription">描述</label>
                <textarea id="serverDescription" name="description" rows="3"></textarea>
            </div>
            <div class="form-actions">
                <button type="button" class="btn btn-secondary" onclick="hideModal('createServerModal')">取消</button>
                <button type="submit" class="btn btn-primary">添加</button>
            </div>
        </form>
    `;
    
    showModal('createServerModal', '添加服务器', content);
}

// 创建服务器
async function createServer(event) {
    event.preventDefault();
    
    const form = event.target;
    const formData = new FormData(form);
    const data = Object.fromEntries(formData.entries());
    
    try {
        const response = await fetch(`${API_BASE}/servers`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(data)
        });
        
        const result = await response.json();
        
        if (result.success) {
            showNotification('服务器添加成功', 'success');
            hideModal('createServerModal');
            loadServers();
        } else {
            showNotification(`添加失败: ${result.message}`, 'error');
        }
    } catch (error) {
        console.error('添加服务器失败:', error);
        showNotification('添加服务器失败', 'error');
    }
}

// 编辑服务器
async function editServer(serverId) {
    try {
        const response = await fetch(`${API_BASE}/servers/${serverId}`);
        const result = await response.json();
        
        if (result.success) {
            const server = result.data;
            const content = `
                <form id="editServerForm" onsubmit="updateServer(event, ${serverId})">
                    <div class="form-group">
                        <label for="editServerName">服务器名称 *</label>
                        <input type="text" id="editServerName" name="name" value="${server.name}" required>
                    </div>
                    <div class="form-group">
                        <label for="editServerUrl">服务器URL *</label>
                        <input type="url" id="editServerUrl" name="url" value="${server.url}" required>
                    </div>
                    <div class="form-group">
                        <label for="editServerDescription">描述</label>
                        <textarea id="editServerDescription" name="description" rows="3">${server.description || ''}</textarea>
                    </div>
                    <div class="form-actions">
                        <button type="button" class="btn btn-secondary" onclick="hideModal('editServerModal')">取消</button>
                        <button type="submit" class="btn btn-primary">更新</button>
                    </div>
                </form>
            `;
            
            showModal('editServerModal', '编辑服务器', content);
        } else {
            showNotification('获取服务器信息失败', 'error');
        }
    } catch (error) {
        console.error('获取服务器信息失败:', error);
        showNotification('获取服务器信息失败', 'error');
    }
}

// 更新服务器
async function updateServer(event, serverId) {
    event.preventDefault();
    
    const form = event.target;
    const formData = new FormData(form);
    const data = Object.fromEntries(formData.entries());
    
    try {
        const response = await fetch(`${API_BASE}/servers/${serverId}`, {
            method: 'PUT',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(data)
        });
        
        const result = await response.json();
        
        if (result.success) {
            showNotification('服务器更新成功', 'success');
            hideModal('editServerModal');
            loadServers();
        } else {
            showNotification(`更新失败: ${result.message}`, 'error');
        }
    } catch (error) {
        console.error('更新服务器失败:', error);
        showNotification('更新服务器失败', 'error');
    }
}

// 删除服务器
async function deleteServer(serverId) {
    if (!confirm('确定要删除这个服务器吗？')) {
        return;
    }
    
    try {
        const response = await fetch(`${API_BASE}/servers/${serverId}`, {
            method: 'DELETE'
        });
        
        const result = await response.json();
        
        if (result.success) {
            showNotification('服务器删除成功', 'success');
            loadServers();
        } else {
            showNotification(`删除失败: ${result.message}`, 'error');
        }
    } catch (error) {
        console.error('删除服务器失败:', error);
        showNotification('删除服务器失败', 'error');
    }
}

// 测试服务器
async function testServer(serverId) {
    try {
        const response = await fetch(`${API_BASE}/servers/${serverId}/test`, {
            method: 'POST'
        });
        
        const result = await response.json();
        
        if (result.success) {
            showNotification('服务器测试成功', 'success');
            loadServers(); // 刷新列表以更新状态
        } else {
            showNotification(`服务器测试失败: ${result.message}`, 'error');
        }
    } catch (error) {
        console.error('测试服务器失败:', error);
        showNotification('测试服务器失败', 'error');
    }
}

// ==================== 通知管理功能 ====================

// 加载通知列表
async function loadNotifications() {
    const container = document.getElementById('notificationsList');
    if (!container) return;
    
    try {
        container.innerHTML = '<div class="loading">加载通知列表...</div>';
        
        const response = await fetch(`${API_BASE}/notifications`);
        const data = await response.json();
        
        if (data.success) {
            container.innerHTML = renderNotificationsTable(data.data || []);
        } else {
            container.innerHTML = '<div class="error">加载通知列表失败</div>';
        }
    } catch (error) {
        console.error('加载通知列表失败:', error);
        container.innerHTML = '<div class="error">加载通知列表失败</div>';
    }
}

// 渲染通知表格
function renderNotificationsTable(notifications) {
    if (notifications.length === 0) {
        return `
            <div class="no-data">
                <p>暂无通知记录</p>
                <button class="btn btn-primary" onclick="showSendNotificationModal()">发送通知</button>
            </div>
        `;
    }
    
    return `
        <div class="table-header">
            <h3>通知列表</h3>
            <button class="btn btn-primary" onclick="showSendNotificationModal()">发送通知</button>
        </div>
        <div class="table-container">
            <table class="data-table">
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>类型</th>
                        <th>标题</th>
                        <th>内容</th>
                        <th>状态</th>
                        <th>创建时间</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody>
                    ${notifications.map(notification => `
                        <tr>
                            <td>${notification.id}</td>
                            <td>${notification.type}</td>
                            <td>${notification.title}</td>
                            <td>${notification.content.substring(0, 50)}${notification.content.length > 50 ? '...' : ''}</td>
                            <td><span class="status-badge ${notification.status}">${notification.status}</span></td>
                            <td>${new Date(notification.created_at).toLocaleString('zh-CN')}</td>
                            <td>
                                <button class="btn btn-sm btn-info" onclick="viewNotification(${notification.id})">查看</button>
                                <button class="btn btn-sm btn-danger" onclick="deleteNotification(${notification.id})">删除</button>
                            </td>
                        </tr>
                    `).join('')}
                </tbody>
            </table>
        </div>
    `;
}

// 显示发送通知模态框
function showSendNotificationModal() {
    const content = `
        <form id="sendNotificationForm" onsubmit="sendNotification(event)">
            <div class="form-group">
                <label for="notificationType">通知类型 *</label>
                <select id="notificationType" name="type" required>
                    <option value="info">信息</option>
                    <option value="warning">警告</option>
                    <option value="error">错误</option>
                    <option value="success">成功</option>
                </select>
            </div>
            <div class="form-group">
                <label for="notificationTitle">标题 *</label>
                <input type="text" id="notificationTitle" name="title" required>
            </div>
            <div class="form-group">
                <label for="notificationContent">内容 *</label>
                <textarea id="notificationContent" name="content" rows="4" required></textarea>
            </div>
            <div class="form-group">
                <label for="notificationTarget">目标用户</label>
                <input type="text" id="notificationTarget" name="target_user" placeholder="留空表示发送给所有用户">
            </div>
            <div class="form-actions">
                <button type="button" class="btn btn-secondary" onclick="hideModal('sendNotificationModal')">取消</button>
                <button type="submit" class="btn btn-primary">发送</button>
            </div>
        </form>
    `;
    
    showModal('sendNotificationModal', '发送通知', content);
}

// 发送通知
async function sendNotification(event) {
    event.preventDefault();
    
    const form = event.target;
    const formData = new FormData(form);
    const data = Object.fromEntries(formData.entries());
    
    try {
        const response = await fetch(`${API_BASE}/notifications`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(data)
        });
        
        const result = await response.json();
        
        if (result.success) {
            showNotification('通知发送成功', 'success');
            hideModal('sendNotificationModal');
            loadNotifications();
        } else {
            showNotification(`发送失败: ${result.message}`, 'error');
        }
    } catch (error) {
        console.error('发送通知失败:', error);
        showNotification('发送通知失败', 'error');
    }
}

// 查看通知详情
async function viewNotification(notificationId) {
    try {
        const response = await fetch(`${API_BASE}/notifications/${notificationId}`);
        const result = await response.json();
        
        if (result.success) {
            const notification = result.data;
            const content = `
                <div class="notification-detail">
                    <div class="detail-item">
                        <label>ID:</label>
                        <span>${notification.id}</span>
                    </div>
                    <div class="detail-item">
                        <label>类型:</label>
                        <span class="status-badge ${notification.type}">${notification.type}</span>
                    </div>
                    <div class="detail-item">
                        <label>标题:</label>
                        <span>${notification.title}</span>
                    </div>
                    <div class="detail-item">
                        <label>内容:</label>
                        <div class="content-text">${notification.content}</div>
                    </div>
                    <div class="detail-item">
                        <label>状态:</label>
                        <span class="status-badge ${notification.status}">${notification.status}</span>
                    </div>
                    <div class="detail-item">
                        <label>创建时间:</label>
                        <span>${new Date(notification.created_at).toLocaleString('zh-CN')}</span>
                    </div>
                    ${notification.target_user ? `
                        <div class="detail-item">
                            <label>目标用户:</label>
                            <span>${notification.target_user}</span>
                        </div>
                    ` : ''}
                </div>
            `;
            
            showModal('viewNotificationModal', '通知详情', content);
        } else {
            showNotification('获取通知详情失败', 'error');
        }
    } catch (error) {
        console.error('获取通知详情失败:', error);
        showNotification('获取通知详情失败', 'error');
    }
}

// 删除通知
async function deleteNotification(notificationId) {
    if (!confirm('确定要删除这个通知吗？')) {
        return;
    }
    
    try {
        const response = await fetch(`${API_BASE}/notifications/${notificationId}`, {
            method: 'DELETE'
        });
        
        const result = await response.json();
        
        if (result.success) {
            showNotification('通知删除成功', 'success');
            loadNotifications();
        } else {
            showNotification(`删除失败: ${result.message}`, 'error');
        }
    } catch (error) {
        console.error('删除通知失败:', error);
        showNotification('删除通知失败', 'error');
    }
}

// ==================== 系统设置功能 ====================

// 加载系统设置
async function loadSystemSettings() {
    const container = document.getElementById('systemSettings');
    if (!container) return;
    
    try {
        container.innerHTML = '<div class="loading">加载系统设置...</div>';
        
        // 获取系统状态和配置
        const [statusResponse, configResponse] = await Promise.all([
            fetch(`${API_BASE}/admin/system/status`),
            fetch(`${API_BASE}/admin/performance/metrics`)
        ]);
        
        const statusData = await statusResponse.json();
        const configData = await configResponse.json();
        
        container.innerHTML = renderSystemSettings(statusData, configData);
    } catch (error) {
        console.error('加载系统设置失败:', error);
        container.innerHTML = '<div class="error">加载系统设置失败</div>';
    }
}

// 保存系统设置
async function saveSystemSettings() {
    try {
        // 这里可以添加保存系统设置的逻辑
        // 目前系统设置主要是只读的，所以这个函数可能不需要实际保存操作
        showNotification('系统设置已保存', 'success');
    } catch (error) {
        console.error('保存系统设置失败:', error);
        showNotification('保存系统设置失败', 'error');
    }
}

// 渲染系统设置
function renderSystemSettings(statusData, configData) {
    const systemInfo = statusData.data || {};
    const performanceData = configData.data || {};
    
    return `
        <div class="system-settings">
            <div class="settings-section">
                <h3>系统状态</h3>
                <div class="status-grid">
                    <div class="status-item">
                        <label>运行时间:</label>
                        <span>${formatUptime(systemInfo.uptime || 0)}</span>
                    </div>
                    <div class="status-item">
                        <label>服务状态:</label>
                        <div class="service-status">
                            ${Object.entries(systemInfo.services || {}).map(([name, status]) => `
                                <span class="status-badge ${status ? 'active' : 'inactive'}">${name}</span>
                            `).join('')}
                        </div>
                    </div>
                </div>
            </div>
            
            <div class="settings-section">
                <h3>性能指标</h3>
                <div class="performance-grid">
                    <div class="metric-item">
                        <label>CPU使用率:</label>
                        <div class="progress-bar">
                            <div class="progress-fill" style="width: ${performanceData.system?.cpu_percent || 0}%"></div>
                            <span>${performanceData.system?.cpu_percent || 0}%</span>
                        </div>
                    </div>
                    <div class="metric-item">
                        <label>内存使用率:</label>
                        <div class="progress-bar">
                            <div class="progress-fill" style="width: ${performanceData.system?.memory_percent || 0}%"></div>
                            <span>${performanceData.system?.memory_percent || 0}%</span>
                        </div>
                    </div>
                    <div class="metric-item">
                        <label>磁盘使用率:</label>
                        <div class="progress-bar">
                            <div class="progress-fill" style="width: ${performanceData.system?.disk_percent || 0}%"></div>
                            <span>${performanceData.system?.disk_percent || 0}%</span>
                        </div>
                    </div>
                </div>
            </div>
            
            <div class="settings-section">
                <h3>系统操作</h3>
                <div class="action-buttons">
                    <button class="btn btn-warning" onclick="restartService()">重启服务</button>
                    <button class="btn btn-info" onclick="forceDiscovery()">强制发现</button>
                    <button class="btn btn-secondary" onclick="systemCleanup()">系统清理</button>
                    <button class="btn btn-danger" onclick="testNotification()">测试通知</button>
                </div>
            </div>
        </div>
    `;
}

// 格式化运行时间
function formatUptime(seconds) {
    const days = Math.floor(seconds / 86400);
    const hours = Math.floor((seconds % 86400) / 3600);
    const minutes = Math.floor((seconds % 3600) / 60);
    
    if (days > 0) {
        return `${days}天 ${hours}小时 ${minutes}分钟`;
    } else if (hours > 0) {
        return `${hours}小时 ${minutes}分钟`;
    } else {
        return `${minutes}分钟`;
    }
}

// 重启服务
async function restartService() {
    if (!confirm('确定要重启服务吗？这可能会影响正在进行的操作。')) {
        return;
    }
    
    try {
        const response = await fetch(`${API_BASE}/admin/system/restart-service`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({ service_name: 'subscription_service' })
        });
        
        const result = await response.json();
        
        if (result.success) {
            showNotification('服务重启成功', 'success');
            setTimeout(() => {
                location.reload();
            }, 2000);
        } else {
            showNotification(`重启失败: ${result.message}`, 'error');
        }
    } catch (error) {
        console.error('重启服务失败:', error);
        showNotification('重启服务失败', 'error');
    }
}

// 强制发现
async function forceDiscovery() {
    try {
        const response = await fetch(`${API_BASE}/admin/discovery/force-run`, {
            method: 'POST'
        });
        
        const result = await response.json();
        
        if (result.success) {
            showNotification('强制发现执行成功', 'success');
            loadSystemSettings();
        } else {
            showNotification(`强制发现失败: ${result.message}`, 'error');
        }
    } catch (error) {
        console.error('强制发现失败:', error);
        showNotification('强制发现失败', 'error');
    }
}

// 系统清理
async function systemCleanup() {
    if (!confirm('确定要执行系统清理吗？这将清理过期数据。')) {
        return;
    }
    
    try {
        const response = await fetch(`${API_BASE}/admin/system/cleanup`, {
            method: 'POST'
        });
        
        const result = await response.json();
        
        if (result.success) {
            showNotification('系统清理完成', 'success');
            loadSystemSettings();
        } else {
            showNotification(`系统清理失败: ${result.message}`, 'error');
        }
    } catch (error) {
        console.error('系统清理失败:', error);
        showNotification('系统清理失败', 'error');
    }
}

// 测试通知
async function testNotification() {
    try {
        const response = await fetch(`${API_BASE}/admin/test/notification`, {
            method: 'POST'
        });
        
        const result = await response.json();
        
        if (result.success) {
            showNotification('测试通知发送成功', 'success');
        } else {
            showNotification(`测试通知失败: ${result.message}`, 'error');
        }
    } catch (error) {
        console.error('测试通知失败:', error);
        showNotification('测试通知失败', 'error');
    }
}

// ==================== 模型管理功能 ====================

// 加载模型列表
async function loadModels() {
    const container = document.getElementById('modelsList');
    if (!container) return;
    
    try {
        container.innerHTML = '<div class="loading">加载模型列表...</div>';
        
        const response = await fetch(`${API_BASE}/models`);
        const data = await response.json();
        
        if (data.success) {
            container.innerHTML = renderModelsTable(data.models || []);
        } else {
            container.innerHTML = '<div class="error">加载模型列表失败</div>';
        }
    } catch (error) {
        console.error('加载模型列表失败:', error);
        container.innerHTML = '<div class="error">加载模型列表失败</div>';
    }
}

// 渲染模型表格
function renderModelsTable(models) {
    if (models.length === 0) {
        return `
            <div class="no-data">
                <p>暂无模型记录</p>
                <button class="btn btn-primary" onclick="showCreateModelModal()">添加模型</button>
            </div>
        `;
    }
    
    return `
        <div class="table-header">
            <h3>模型列表</h3>
            <button class="btn btn-primary" onclick="showCreateModelModal()">添加模型</button>
        </div>
        <div class="table-container">
            <table class="data-table">
                <thead>
                    <tr>
                        <th>名称</th>
                        <th>版本</th>
                        <th>类型</th>
                        <th>状态</th>
                        <th>大小</th>
                        <th>服务器</th>
                        <th>更新时间</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody>
                    ${models.map(model => `
                        <tr>
                            <td>${model.name}</td>
                            <td>${model.version}</td>
                            <td><span class="model-type-badge ${model.model_type}">${model.model_type}</span></td>
                             <td>
                                 <select class="status-select" data-model-id="${model.id}" onchange="updateModelStatus('${model.id}', this.value)">
                                     <option value="draft" ${model.status === 'draft' ? 'selected' : ''}>草稿</option>
                                     <option value="testing" ${model.status === 'testing' ? 'selected' : ''}>测试中</option>
                                     <option value="published" ${model.status === 'published' ? 'selected' : ''}>已发布</option>
                                     <option value="deprecated" ${model.status === 'deprecated' ? 'selected' : ''}>已弃用</option>
                                     <option value="archived" ${model.status === 'archived' ? 'selected' : ''}>已归档</option>
                                     <option value="removed" ${model.status === 'removed' ? 'selected' : ''}>已移除</option>
                                     <option value="maintenance" ${model.status === 'maintenance' ? 'selected' : ''}>维护中</option>
                                     <option value="suspended" ${model.status === 'suspended' ? 'selected' : ''}>暂停服务</option>
                                 </select>
                             </td>
                            <td>${model.size || 'N/A'}</td>
                            <td class="server-cell">${model.server_id ? model.server_id.substring(0, 8) + '...' : 'N/A'}</td>
                            <td>${model.last_update ? new Date(model.last_update).toLocaleString('zh-CN') : 'N/A'}</td>
                            <td>
                                <button class="btn btn-sm btn-info" onclick="viewModel('${model.id}')">查看</button>
                                <button class="btn btn-sm btn-secondary" onclick="editModel('${model.id}')">编辑</button>
                                <button class="btn btn-sm btn-danger" onclick="deleteModel('${model.id}')">删除</button>
                            </td>
                        </tr>
                    `).join('')}
                </tbody>
            </table>
        </div>
    `;
}

// 格式化文件大小
function formatFileSize(bytes) {
    if (bytes === 0) return '0 B';
    const k = 1024;
    const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
}

// 显示创建模型模态框
function showCreateModelModal() {
    const content = `
        <form id="createModelForm" onsubmit="createModel(event)">
            <div class="form-group">
                <label for="modelName">模型名称 *</label>
                <input type="text" id="modelName" name="name" required>
            </div>
            <div class="form-group">
                <label for="modelVersion">版本 *</label>
                <input type="text" id="modelVersion" name="version" value="1.0.0" required>
            </div>
            <div class="form-group">
                <label for="modelType">模型类型 *</label>
                <select id="modelType" name="model_type" required>
                    <option value="detection">目标检测</option>
                    <option value="segmentation">图像分割</option>
                    <option value="classification">图像分类</option>
                    <option value="pose">姿态估计</option>
                </select>
            </div>
            <div class="form-group">
                <label for="modelStatus">模型状态 *</label>
                <select id="modelStatus" name="status" required>
                    <option value="draft">草稿</option>
                    <option value="testing">测试中</option>
                    <option value="published">已发布</option>
                    <option value="deprecated">已弃用</option>
                    <option value="archived">已归档</option>
                    <option value="removed">已移除</option>
                    <option value="maintenance">维护中</option>
                    <option value="suspended">暂停服务</option>
                </select>
            </div>
            <div class="form-group">
                <label for="modelDescription">描述</label>
                <textarea id="modelDescription" name="description" rows="3"></textarea>
            </div>
            <div class="form-group">
                <label for="modelAuthor">作者</label>
                <input type="text" id="modelAuthor" name="author">
            </div>
            <div class="form-group">
                <label for="downloadUrl">下载URL *</label>
                <input type="url" id="downloadUrl" name="download_url" required>
            </div>
            <div class="form-group">
                <label for="modelTags">标签 (用逗号分隔)</label>
                <input type="text" id="modelTags" name="tags" placeholder="yolo,detection,nano">
            </div>
            <div class="form-actions">
                <button type="button" class="btn btn-secondary" onclick="hideModal('createModelModal')">取消</button>
                <button type="submit" class="btn btn-primary">创建</button>
            </div>
        </form>
    `;
    
    showModal('createModelModal', '添加模型', content);
}

// 创建模型
async function createModel(event) {
    event.preventDefault();
    
    const form = event.target;
    const formData = new FormData(form);
    const data = Object.fromEntries(formData.entries());
    
    // 处理标签
    if (data.tags) {
        data.tags = data.tags.split(',').map(tag => tag.trim()).filter(tag => tag);
    }
    
    try {
        const response = await fetch(`${API_BASE}/models`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(data)
        });
        
        const result = await response.json();
        
        if (result.success) {
            showNotification('模型创建成功', 'success');
            hideModal('createModelModal');
            loadModels();
        } else {
            showNotification(`创建失败: ${result.message}`, 'error');
        }
    } catch (error) {
        console.error('创建模型失败:', error);
        showNotification('创建模型失败', 'error');
    }
}

// 查看模型详情
async function viewModel(modelId) {
    try {
        const response = await fetch(`${API_BASE}/models/${modelId}`);
        const result = await response.json();
        
        if (result.success) {
            const model = result.data;
            const content = `
                <div class="model-detail">
                    <div class="detail-item">
                        <label>ID:</label>
                        <span>${model.id}</span>
                    </div>
                    <div class="detail-item">
                        <label>名称:</label>
                        <span>${model.name}</span>
                    </div>
                    <div class="detail-item">
                        <label>版本:</label>
                        <span>${model.version}</span>
                    </div>
                    <div class="detail-item">
                        <label>类型:</label>
                        <span class="model-type-badge ${model.model_type}">${model.model_type}</span>
                    </div>
                    <div class="detail-item">
                        <label>状态:</label>
                        <span class="status-badge ${model.status}">${model.status}</span>
                    </div>
                    <div class="detail-item">
                        <label>大小:</label>
                        <span>${model.size || 'N/A'}</span>
                    </div>
                    <div class="detail-item">
                        <label>作者:</label>
                        <span>${model.author || 'N/A'}</span>
                    </div>
                    <div class="detail-item">
                        <label>描述:</label>
                        <div class="content-text">${model.description || 'N/A'}</div>
                    </div>
                    <div class="detail-item">
                        <label>下载URL:</label>
                        <div class="content-text">${model.download_url || 'N/A'}</div>
                    </div>
                    <div class="detail-item">
                        <label>标签:</label>
                        <span>${model.tags ? model.tags.join(', ') : 'N/A'}</span>
                    </div>
                    <div class="detail-item">
                        <label>创建时间:</label>
                        <span>${model.upload_time ? new Date(model.upload_time).toLocaleString('zh-CN') : 'N/A'}</span>
                    </div>
                    <div class="detail-item">
                        <label>更新时间:</label>
                        <span>${model.last_update ? new Date(model.last_update).toLocaleString('zh-CN') : 'N/A'}</span>
                    </div>
                </div>
            `;
            
            showModal('viewModelModal', '模型详情', content);
        } else {
            showNotification('获取模型详情失败', 'error');
        }
    } catch (error) {
        console.error('获取模型详情失败:', error);
        showNotification('获取模型详情失败', 'error');
    }
}

// 编辑模型
async function editModel(modelId) {
    try {
        const response = await fetch(`${API_BASE}/models/${modelId}`);
        const result = await response.json();
        
        if (result.success) {
            const model = result.data;
            const content = `
                <form id="editModelForm" onsubmit="updateModel(event, '${modelId}')">
                    <div class="form-group">
                        <label for="editModelName">模型名称 *</label>
                        <input type="text" id="editModelName" name="name" value="${model.name}" required>
                    </div>
                    <div class="form-group">
                        <label for="editModelVersion">版本 *</label>
                        <input type="text" id="editModelVersion" name="version" value="${model.version}" required>
                    </div>
                    <div class="form-group">
                        <label for="editModelType">模型类型 *</label>
                        <select id="editModelType" name="model_type" required>
                            <option value="detection" ${model.model_type === 'detection' ? 'selected' : ''}>目标检测</option>
                            <option value="segmentation" ${model.model_type === 'segmentation' ? 'selected' : ''}>图像分割</option>
                            <option value="classification" ${model.model_type === 'classification' ? 'selected' : ''}>图像分类</option>
                            <option value="pose" ${model.model_type === 'pose' ? 'selected' : ''}>姿态估计</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label for="editModelStatus">模型状态 *</label>
                        <select id="editModelStatus" name="status" required>
                            <option value="draft" ${model.status === 'draft' ? 'selected' : ''}>草稿</option>
                            <option value="testing" ${model.status === 'testing' ? 'selected' : ''}>测试中</option>
                            <option value="published" ${model.status === 'published' ? 'selected' : ''}>已发布</option>
                            <option value="deprecated" ${model.status === 'deprecated' ? 'selected' : ''}>已弃用</option>
                            <option value="archived" ${model.status === 'archived' ? 'selected' : ''}>已归档</option>
                            <option value="removed" ${model.status === 'removed' ? 'selected' : ''}>已移除</option>
                            <option value="maintenance" ${model.status === 'maintenance' ? 'selected' : ''}>维护中</option>
                            <option value="suspended" ${model.status === 'suspended' ? 'selected' : ''}>暂停服务</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label for="editModelDescription">描述</label>
                        <textarea id="editModelDescription" name="description" rows="3">${model.description || ''}</textarea>
                    </div>
                    <div class="form-group">
                        <label for="editModelAuthor">作者</label>
                        <input type="text" id="editModelAuthor" name="author" value="${model.author || ''}">
                    </div>
                    <div class="form-group">
                        <label for="editDownloadUrl">下载URL *</label>
                        <input type="url" id="editDownloadUrl" name="download_url" value="${model.download_url}" required>
                    </div>
                    <div class="form-group">
                        <label for="editModelTags">标签 (用逗号分隔)</label>
                        <input type="text" id="editModelTags" name="tags" value="${model.tags ? model.tags.join(', ') : ''}" placeholder="yolo,detection,nano">
                    </div>
                    <div class="form-actions">
                        <button type="button" class="btn btn-secondary" onclick="hideModal('editModelModal')">取消</button>
                        <button type="submit" class="btn btn-primary">更新</button>
                    </div>
                </form>
            `;
            
            showModal('editModelModal', '编辑模型', content);
        } else {
            showNotification('获取模型信息失败', 'error');
        }
    } catch (error) {
        console.error('获取模型信息失败:', error);
        showNotification('获取模型信息失败', 'error');
    }
}

// 更新模型
async function updateModel(event, modelId) {
    event.preventDefault();
    
    const form = event.target;
    const formData = new FormData(form);
    const data = Object.fromEntries(formData.entries());
    
    // 处理标签
    if (data.tags) {
        data.tags = data.tags.split(',').map(tag => tag.trim()).filter(tag => tag);
    }
    
    try {
        const response = await fetch(`${API_BASE}/models/${modelId}`, {
            method: 'PUT',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(data)
        });
        
        const result = await response.json();
        
        if (result.success) {
            showNotification('模型更新成功', 'success');
            hideModal('editModelModal');
            loadModels();
        } else {
            showNotification(`更新失败: ${result.message}`, 'error');
        }
    } catch (error) {
        console.error('更新模型失败:', error);
        showNotification('更新模型失败', 'error');
    }
}

// 删除模型
async function deleteModel(modelId) {
    if (!confirm('确定要删除这个模型吗？')) {
        return;
    }

    try {
        const response = await fetch(`${API_BASE}/models/${modelId}`, {
            method: 'DELETE'
        });

        const result = await response.json();

        if (result.success) {
            showNotification('模型删除成功', 'success');
            loadModels();
        } else {
            showNotification(`删除失败: ${result.message}`, 'error');
        }
    } catch (error) {
        console.error('删除模型失败:', error);
        showNotification('删除模型失败', 'error');
    }
}

// 更新模型状态
async function updateModelStatus(modelId, newStatus) {
    try {
        // 显示加载状态
        const selectElement = document.querySelector(`select[data-model-id="${modelId}"]`);
        if (selectElement) {
            selectElement.disabled = true;
        }

        const response = await fetch(`${API_BASE}/models/${modelId}/status`, {
            method: 'PUT',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                status: newStatus
            })
        });

        const result = await response.json();

        if (result.success) {
            showNotification(`模型状态已更新为: ${getStatusDisplayName(newStatus)}`, 'success');
            // 不需要重新加载整个列表，只需要重新启用下拉框
            if (selectElement) {
                selectElement.disabled = false;
            }
        } else {
            showNotification(`状态更新失败: ${result.message}`, 'error');
            // 恢复原来的状态
            if (selectElement) {
                selectElement.disabled = false;
                // 可以考虑恢复到原来的值，但这需要保存原始状态
                loadModels(); // 重新加载以确保状态一致
            }
        }
    } catch (error) {
        console.error('更新模型状态失败:', error);
        showNotification('更新模型状态失败', 'error');

        // 重新启用下拉框并重新加载数据
        const selectElement = document.querySelector(`select[data-model-id="${modelId}"]`);
        if (selectElement) {
            selectElement.disabled = false;
        }
        loadModels();
    }
}

// 获取状态显示名称
function getStatusDisplayName(status) {
    const statusMap = {
        'draft': '草稿',
        'testing': '测试中',
        'published': '已发布',
        'deprecated': '已弃用',
        'archived': '已归档',
        'removed': '已移除',
        'maintenance': '维护中',
        'suspended': '暂停服务'
    };
    return statusMap[status] || status;
}

// 触发模型发现
async function triggerModelDiscovery() {
    try {
        const response = await fetch(`${API_BASE}/discovery/trigger`, {
            method: 'POST'
        });
        
        const result = await response.json();
        
        if (result.success) {
            showNotification('模型发现已触发', 'success');
            // 延迟刷新模型列表
            setTimeout(() => {
                loadModels();
            }, 2000);
        } else {
            showNotification(`触发发现失败: ${result.message}`, 'error');
        }
    } catch (error) {
        console.error('触发模型发现失败:', error);
        showNotification('触发模型发现失败', 'error');
    }
}

// ==================== WebSocket实时通信 ====================

// 初始化WebSocket连接
function initializeWebSocket() {
    console.log('🔌 初始化WebSocket连接...');
    
    try {
        // 构建WebSocket URL
        const wsUrl = `${WS_BASE}/admin`;
        console.log('🌐 WebSocket URL:', wsUrl);
        
        // 创建WebSocket连接
        websocket = new WebSocket(wsUrl);
        
        // 连接打开事件
        websocket.onopen = function(event) {
            console.log('✅ WebSocket连接已建立');
            reconnectAttempts = 0;
            updateConnectionStatus('connected');
        };
        
        // 消息接收事件
        websocket.onmessage = function(event) {
            try {
                const data = JSON.parse(event.data);
                console.log('📨 收到WebSocket消息:', data);
                handleWebSocketMessage(data);
            } catch (error) {
                console.error('❌ 解析WebSocket消息失败:', error);
            }
        };
        
        // 连接关闭事件
        websocket.onclose = function(event) {
            console.log('🔌 WebSocket连接已关闭:', event.code, event.reason);
            updateConnectionStatus('disconnected');
            
            // 自动重连
            if (reconnectAttempts < maxReconnectAttempts) {
                reconnectAttempts++;
                console.log(`🔄 尝试重连 (${reconnectAttempts}/${maxReconnectAttempts})...`);
                setTimeout(() => {
                    initializeWebSocket();
                }, 3000 * reconnectAttempts);
            } else {
                console.error('❌ WebSocket重连失败，已达到最大重试次数');
                updateConnectionStatus('failed');
            }
        };
        
        // 连接错误事件
        websocket.onerror = function(error) {
            console.error('❌ WebSocket连接错误:', error);
            updateConnectionStatus('error');
        };
        
    } catch (error) {
        console.error('❌ 初始化WebSocket失败:', error);
        updateConnectionStatus('error');
    }
}

// 处理WebSocket消息
function handleWebSocketMessage(data) {
    switch(data.type) {
        case 'model_update':
            console.log('🔄 模型更新通知:', data);
            handleModelUpdateNotification(data);
            break;
            
        case 'model_discovered':
            console.log('🆕 模型发现通知:', data);
            handleModelDiscoveredNotification(data);
            break;
            
        case 'subscription_update':
            console.log('📋 订阅更新通知:', data);
            handleSubscriptionUpdateNotification(data);
            break;
            
        case 'server_status_change':
            console.log('🖥️ 服务器状态变化:', data);
            handleServerStatusChange(data);
            break;
            
        case 'system_announcement':
            console.log('📢 系统公告:', data);
            handleSystemAnnouncement(data);
            break;
            
        case 'notification':
            console.log('🔔 通知消息:', data);
            handleNotificationMessage(data);
            break;
            
        default:
            console.log('❓ 未知消息类型:', data);
    }
}

// 处理模型更新通知
function handleModelUpdateNotification(data) {
    const message = `模型 ${data.model_name} 已更新到版本 ${data.data?.version || '最新版本'}`;
    showNotification(message, 'info');
    
    // 如果当前在模型管理页面，刷新模型列表
    if (currentTab === 'models') {
        loadModels();
    }
    
    // 如果当前在仪表板页面，刷新仪表板数据
    if (currentTab === 'dashboard') {
        loadDashboardData();
    }
}

// 处理模型发现通知
function handleModelDiscoveredNotification(data) {
    const message = `发现新模型: ${data.model_name}`;
    showNotification(message, 'success');
    
    // 如果当前在模型管理页面，刷新模型列表
    if (currentTab === 'models') {
        loadModels();
    }
}

// 处理订阅更新通知
function handleSubscriptionUpdateNotification(data) {
    const message = `订阅状态更新: ${data.subscription_id}`;
    showNotification(message, 'info');
    
    // 如果当前在订阅管理页面，刷新订阅列表
    if (currentTab === 'subscriptions') {
        loadSubscriptions();
    }
}

// 处理服务器状态变化
function handleServerStatusChange(data) {
    const status = data.status === 'online' ? '在线' : '离线';
    const message = `服务器 ${data.server_name} 状态变化: ${status}`;
    showNotification(message, data.status === 'online' ? 'success' : 'warning');
    
    // 如果当前在服务器管理页面，刷新服务器列表
    if (currentTab === 'servers') {
        loadServers();
    }
    
    // 如果当前在仪表板页面，刷新仪表板数据
    if (currentTab === 'dashboard') {
        loadDashboardData();
    }
}

// 处理系统公告
function handleSystemAnnouncement(data) {
    const message = `系统公告: ${data.message}`;
    showNotification(message, 'info');
}

// 处理通知消息
function handleNotificationMessage(data) {
    const message = data.message || '收到新通知';
    showNotification(message, data.level || 'info');
}

// 更新连接状态
function updateConnectionStatus(status) {
    const statusIndicator = document.getElementById('systemStatus');
    if (!statusIndicator) return;
    
    const statusText = statusIndicator.querySelector('.status-text');
    const statusDot = statusIndicator.querySelector('.status-dot');
    
    // 移除所有状态类
    statusDot.classList.remove('healthy', 'error');
    
    switch(status) {
        case 'connected':
            statusText.textContent = '实时连接';
            statusDot.classList.add('healthy');
            break;
        case 'disconnected':
            statusText.textContent = '连接断开';
            statusDot.classList.add('error');
            break;
        case 'error':
            statusText.textContent = '连接错误';
            statusDot.classList.add('error');
            break;
        case 'failed':
            statusText.textContent = '连接失败';
            statusDot.classList.add('error');
            break;
        default:
            statusText.textContent = '检查中...';
    }
}

// 发送WebSocket消息
function sendWebSocketMessage(message) {
    if (websocket && websocket.readyState === WebSocket.OPEN) {
        websocket.send(JSON.stringify(message));
        console.log('📤 发送WebSocket消息:', message);
    } else {
        console.warn('⚠️ WebSocket未连接，无法发送消息');
    }
}

// 关闭WebSocket连接
function closeWebSocket() {
    if (websocket) {
        websocket.close();
        websocket = null;
        console.log('🔌 WebSocket连接已关闭');
    }
}

// 页面卸载时关闭WebSocket连接
window.addEventListener('beforeunload', function() {
    closeWebSocket();
});

// ==================== 客户端管理功能 ====================

// 加载客户端列表
async function loadClients() {
    console.log('📱 加载客户端列表...');
    
    const clientsList = document.getElementById('clientsList');
    if (!clientsList) return;
    
    try {
        const response = await fetch(`${API_BASE}/clients`);
        const data = await response.json();
        
        if (data.success) {
            renderClientsList(data.clients);
        } else {
            clientsList.innerHTML = '<div class="error">加载客户端列表失败</div>';
        }
    } catch (error) {
        console.error('加载客户端列表失败:', error);
        clientsList.innerHTML = '<div class="error">加载客户端列表失败: ' + error.message + '</div>';
    }
}

// 渲染客户端列表
function renderClientsList(clients) {
    const clientsList = document.getElementById('clientsList');
    if (!clientsList) return;
    
    if (!clients || clients.length === 0) {
        clientsList.innerHTML = '<div class="no-data">暂无注册的客户端</div>';
        return;
    }
    
    clientsList.innerHTML = `
        <div class="data-table">
            <table>
                <thead>
                    <tr>
                        <th>客户端名称</th>
                        <th>主机名</th>
                        <th>IP地址</th>
                        <th>端口</th>
                        <th>版本</th>
                        <th>状态</th>
                        <th>注册时间</th>
                        <th>最后活跃</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody>
                    ${clients.map(client => `
                        <tr>
                            <td>
                                <div class="client-info">
                                    <div class="client-name">${client.client_name}</div>
                                    <div class="client-id">${client.client_id}</div>
                                </div>
                            </td>
                            <td>${client.hostname}</td>
                            <td>${client.ip_address}</td>
                            <td>${client.port}</td>
                            <td>${client.version}</td>
                            <td><span class="status-badge ${client.status}">${client.status}</span></td>
                            <td>${new Date(client.registered_at * 1000).toLocaleString('zh-CN')}</td>
                            <td>${new Date(client.last_seen * 1000).toLocaleString('zh-CN')}</td>
                            <td>
                                <button class="btn btn-sm btn-info" onclick="viewClientDetails('${client.id}')">详情</button>
                                <button class="btn btn-sm btn-warning" onclick="deleteClient('${client.id}')">删除</button>
                            </td>
                        </tr>
                    `).join('')}
                </tbody>
            </table>
        </div>
    `;
}

// 查看客户端详情
async function viewClientDetails(clientId) {
    try {
        const response = await fetch(`${API_BASE}/clients/${clientId}`);
        const data = await response.json();
        
        if (data.success) {
            showClientDetailsModal(data);
        } else {
            showNotification('获取客户端详情失败', 'error');
        }
    } catch (error) {
        console.error('获取客户端详情失败:', error);
        showNotification('获取客户端详情失败: ' + error.message, 'error');
    }
}

// 显示客户端详情模态框
function showClientDetailsModal(client) {
    const modal = document.getElementById('viewClientModal');
    if (!modal) return;
    
    const modalContent = modal.querySelector('.modal-content');
    modalContent.innerHTML = `
        <div class="client-details">
            <h3>客户端详情</h3>
            <div class="detail-grid">
                <div class="detail-item">
                    <label>客户端ID:</label>
                    <span>${client.client_id}</span>
                </div>
                <div class="detail-item">
                    <label>客户端名称:</label>
                    <span>${client.client_name}</span>
                </div>
                <div class="detail-item">
                    <label>主机名:</label>
                    <span>${client.hostname}</span>
                </div>
                <div class="detail-item">
                    <label>IP地址:</label>
                    <span>${client.ip_address}</span>
                </div>
                <div class="detail-item">
                    <label>端口:</label>
                    <span>${client.port}</span>
                </div>
                <div class="detail-item">
                    <label>版本:</label>
                    <span>${client.version}</span>
                </div>
                <div class="detail-item">
                    <label>状态:</label>
                    <span class="status-badge ${client.status}">${client.status}</span>
                </div>
                <div class="detail-item">
                    <label>能力:</label>
                    <span>${client.capabilities.join(', ')}</span>
                </div>
                <div class="detail-item">
                    <label>描述:</label>
                    <span>${client.description || '无'}</span>
                </div>
                <div class="detail-item">
                    <label>联系信息:</label>
                    <span>${client.contact_info || '无'}</span>
                </div>
                <div class="detail-item">
                    <label>注册时间:</label>
                    <span>${new Date(client.registered_at * 1000).toLocaleString('zh-CN')}</span>
                </div>
                <div class="detail-item">
                    <label>最后活跃:</label>
                    <span>${new Date(client.last_seen * 1000).toLocaleString('zh-CN')}</span>
                </div>
            </div>
        </div>
    `;
    
    modal.style.display = 'flex';
}

// 删除客户端
async function deleteClient(clientId) {
    if (!confirm('确定要删除这个客户端吗？')) return;
    
    try {
        const response = await fetch(`${API_BASE}/clients/${clientId}`, {
            method: 'DELETE'
        });
        const data = await response.json();
        
        if (data.success) {
            showNotification('客户端删除成功', 'success');
            loadClients(); // 重新加载列表
        } else {
            showNotification('删除客户端失败: ' + data.message, 'error');
        }
    } catch (error) {
        console.error('删除客户端失败:', error);
        showNotification('删除客户端失败: ' + error.message, 'error');
    }
}

// 刷新客户端列表
async function refreshClients() {
    await loadClients();
    showNotification('客户端列表已刷新', 'success');
}

// ==================== 模型状态管理功能 ====================

// 加载模型状态统计
async function loadModelStatusStats() {
    try {
        const response = await fetch(`${API_BASE}/model-status/statistics`);
        const data = await response.json();
        
        if (data.success) {
            renderModelStatusStats(data.statistics);
        } else {
            throw new Error(data.message || '获取统计信息失败');
        }
    } catch (error) {
        console.error('加载模型状态统计失败:', error);
        document.getElementById('modelStatusStats').innerHTML = `
            <div class="error">加载统计信息失败: ${error.message}</div>
        `;
    }
}

// 渲染模型状态统计
function renderModelStatusStats(stats) {
    const container = document.getElementById('modelStatusStats');
    
    container.innerHTML = `
        <div class="stats-grid">
            <div class="stat-card">
                <div class="stat-number">${stats.total_models}</div>
                <div class="stat-label">总模型数</div>
            </div>
            <div class="stat-card">
                <div class="stat-number">${stats.unique_clients}</div>
                <div class="stat-label">客户端数</div>
            </div>
            <div class="stat-card">
                <div class="stat-number">${stats.unique_models}</div>
                <div class="stat-label">唯一模型数</div>
            </div>
            <div class="stat-card">
                <div class="stat-number">${stats.status_distribution.active || 0}</div>
                <div class="stat-label">运行中</div>
            </div>
            <div class="stat-card">
                <div class="stat-number">${stats.status_distribution.loaded || 0}</div>
                <div class="stat-label">已加载</div>
            </div>
            <div class="stat-card">
                <div class="stat-number">${stats.status_distribution.error || 0}</div>
                <div class="stat-label">错误</div>
            </div>
        </div>
        
        <div class="stats-details">
            <div class="detail-section">
                <h4>状态分布</h4>
                <div class="status-distribution">
                    ${Object.entries(stats.status_distribution).map(([status, count]) => `
                        <div class="status-item">
                            <span class="status-label">${getStatusLabel(status)}:</span>
                            <span class="status-count">${count}</span>
                        </div>
                    `).join('')}
                </div>
            </div>
            
            <div class="detail-section">
                <h4>类型分布</h4>
                <div class="type-distribution">
                    ${Object.entries(stats.type_distribution).map(([type, count]) => `
                        <div class="type-item">
                            <span class="type-label">${getTypeLabel(type)}:</span>
                            <span class="type-count">${count}</span>
                        </div>
                    `).join('')}
                </div>
            </div>
        </div>
    `;
}

// 加载模型状态列表
async function loadModelStatus() {
    try {
        const response = await fetch(`${API_BASE}/model-status/all`);
        const data = await response.json();
        
        if (data.success) {
            renderModelStatusList(data.model_statuses);
        } else {
            throw new Error(data.message || '获取模型状态失败');
        }
    } catch (error) {
        console.error('加载模型状态失败:', error);
        document.getElementById('modelStatusList').innerHTML = `
            <div class="error">加载模型状态失败: ${error.message}</div>
        `;
    }
}

// 渲染模型状态列表
function renderModelStatusList(modelStatuses) {
    const container = document.getElementById('modelStatusList');
    
    if (modelStatuses.length === 0) {
        container.innerHTML = '<div class="empty">暂无模型状态数据</div>';
        return;
    }
    
    container.innerHTML = `
        <div class="table-container">
            <table class="data-table">
                <thead>
                    <tr>
                        <th>客户端ID</th>
                        <th>模型名称</th>
                        <th>模型类型</th>
                        <th>状态</th>
                        <th>文件大小</th>
                        <th>使用次数</th>
                        <th>最后更新</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody>
                    ${modelStatuses.map(status => `
                        <tr>
                            <td>${status.client_id}</td>
                            <td>${status.model_name}</td>
                            <td>${getTypeLabel(status.model_type)}</td>
                            <td><span class="status-badge ${status.status}">${getStatusLabel(status.status)}</span></td>
                            <td>${status.file_size ? formatFileSize(status.file_size) : 'N/A'}</td>
                            <td>${status.usage_count || 0}</td>
                            <td>${new Date(status.last_updated * 1000).toLocaleString('zh-CN')}</td>
                            <td>
                                <button class="btn btn-sm btn-info" onclick="viewModelStatusDetails('${status.id}')">详情</button>
                                <button class="btn btn-sm btn-warning" onclick="deleteModelStatus('${status.id}')">删除</button>
                            </td>
                        </tr>
                    `).join('')}
                </tbody>
            </table>
        </div>
    `;
}

// 查看模型状态详情
async function viewModelStatusDetails(statusId) {
    try {
        const response = await fetch(`${API_BASE}/model-status/${statusId}`);
        const data = await response.json();
        
        if (data.success) {
            showModelStatusDetailsModal(data);
        } else {
            showNotification('获取模型状态详情失败', 'error');
        }
    } catch (error) {
        console.error('获取模型状态详情失败:', error);
        showNotification('获取模型状态详情失败: ' + error.message, 'error');
    }
}

// 显示模型状态详情模态框
function showModelStatusDetailsModal(status) {
    const modal = document.getElementById('viewModelStatusModal');
    if (!modal) return;
    
    const modalContent = modal.querySelector('.modal-content');
    modalContent.innerHTML = `
        <div class="model-status-details">
            <h3>模型状态详情</h3>
            <div class="detail-grid">
                <div class="detail-item">
                    <label>客户端ID:</label>
                    <span>${status.client_id}</span>
                </div>
                <div class="detail-item">
                    <label>模型名称:</label>
                    <span>${status.model_name}</span>
                </div>
                <div class="detail-item">
                    <label>模型类型:</label>
                    <span>${getTypeLabel(status.model_type)}</span>
                </div>
                <div class="detail-item">
                    <label>模型大小:</label>
                    <span>${status.model_size || 'N/A'}</span>
                </div>
                <div class="detail-item">
                    <label>模型版本:</label>
                    <span>${status.model_version || 'N/A'}</span>
                </div>
                <div class="detail-item">
                    <label>状态:</label>
                    <span class="status-badge ${status.status}">${getStatusLabel(status.status)}</span>
                </div>
                <div class="detail-item">
                    <label>文件路径:</label>
                    <span>${status.file_path || 'N/A'}</span>
                </div>
                <div class="detail-item">
                    <label>文件大小:</label>
                    <span>${status.file_size ? formatFileSize(status.file_size) : 'N/A'}</span>
                </div>
                <div class="detail-item">
                    <label>上传时间:</label>
                    <span>${status.upload_time ? new Date(status.upload_time * 1000).toLocaleString('zh-CN') : 'N/A'}</span>
                </div>
                <div class="detail-item">
                    <label>最后使用:</label>
                    <span>${status.last_used ? new Date(status.last_used * 1000).toLocaleString('zh-CN') : 'N/A'}</span>
                </div>
                <div class="detail-item">
                    <label>使用次数:</label>
                    <span>${status.usage_count || 0}</span>
                </div>
                <div class="detail-item">
                    <label>汇报时间:</label>
                    <span>${new Date(status.reported_at * 1000).toLocaleString('zh-CN')}</span>
                </div>
                <div class="detail-item">
                    <label>最后更新:</label>
                    <span>${new Date(status.last_updated * 1000).toLocaleString('zh-CN')}</span>
                </div>
                ${status.error_message ? `
                    <div class="detail-item">
                        <label>错误信息:</label>
                        <span class="error-message">${status.error_message}</span>
                    </div>
                ` : ''}
                ${Object.keys(status.performance_metrics).length > 0 ? `
                    <div class="detail-item">
                        <label>性能指标:</label>
                        <div class="performance-metrics">
                            ${Object.entries(status.performance_metrics).map(([key, value]) => `
                                <div class="metric-item">
                                    <span class="metric-key">${key}:</span>
                                    <span class="metric-value">${value}</span>
                                </div>
                            `).join('')}
                        </div>
                    </div>
                ` : ''}
                ${Object.keys(status.system_info).length > 0 ? `
                    <div class="detail-item">
                        <label>系统信息:</label>
                        <div class="system-info">
                            ${Object.entries(status.system_info).map(([key, value]) => `
                                <div class="info-item">
                                    <span class="info-key">${key}:</span>
                                    <span class="info-value">${value}</span>
                                </div>
                            `).join('')}
                        </div>
                    </div>
                ` : ''}
            </div>
        </div>
    `;
    
    modal.style.display = 'flex';
}

// 删除模型状态
async function deleteModelStatus(statusId) {
    if (!confirm('确定要删除这个模型状态吗？')) return;
    
    try {
        const response = await fetch(`${API_BASE}/model-status/${statusId}`, {
            method: 'DELETE'
        });
        const data = await response.json();
        
        if (data.success) {
            showNotification('模型状态删除成功', 'success');
            loadModelStatus(); // 重新加载列表
        } else {
            showNotification('删除模型状态失败: ' + data.message, 'error');
        }
    } catch (error) {
        console.error('删除模型状态失败:', error);
        showNotification('删除模型状态失败: ' + error.message, 'error');
    }
}

// 刷新模型状态
async function refreshModelStatus() {
    await loadModelStatusStats();
    await loadModelStatus();
    showNotification('模型状态已刷新', 'success');
}

// 导出模型状态
async function exportModelStatus() {
    try {
        const response = await fetch(`${API_BASE}/model-status/all`);
        const data = await response.json();
        
        if (data.success) {
            const csvContent = generateModelStatusCSV(data.model_statuses);
            downloadCSV(csvContent, 'model_status_export.csv');
            showNotification('模型状态导出成功', 'success');
        } else {
            showNotification('导出模型状态失败: ' + data.message, 'error');
        }
    } catch (error) {
        console.error('导出模型状态失败:', error);
        showNotification('导出模型状态失败: ' + error.message, 'error');
    }
}

// 生成模型状态CSV
function generateModelStatusCSV(modelStatuses) {
    const headers = [
        '客户端ID', '模型名称', '模型类型', '状态', '文件大小', 
        '使用次数', '汇报时间', '最后更新'
    ];
    
    const rows = modelStatuses.map(status => [
        status.client_id,
        status.model_name,
        getTypeLabel(status.model_type),
        getStatusLabel(status.status),
        status.file_size ? formatFileSize(status.file_size) : 'N/A',
        status.usage_count || 0,
        new Date(status.reported_at * 1000).toLocaleString('zh-CN'),
        new Date(status.last_updated * 1000).toLocaleString('zh-CN')
    ]);
    
    return [headers, ...rows].map(row => 
        row.map(cell => `"${cell}"`).join(',')
    ).join('\n');
}

// 应用模型状态筛选
function applyModelStatusFilter() {
    const clientId = document.getElementById('filterClientId').value;
    const modelType = document.getElementById('filterModelType').value;
    const status = document.getElementById('filterStatus').value;
    
    // 这里可以实现筛选逻辑
    console.log('应用筛选:', { clientId, modelType, status });
    showNotification('筛选功能开发中', 'info');
}

// 清除模型状态筛选
function clearModelStatusFilter() {
    document.getElementById('filterClientId').value = '';
    document.getElementById('filterModelType').value = '';
    document.getElementById('filterStatus').value = '';
    showNotification('筛选已清除', 'info');
}

// ==================== 模型分发功能 ====================

// 显示模型分发表单
function showDispatchModelForm() {
    console.log('🚀 显示模型分发表单');
    // 表单已经在HTML中，只需要滚动到表单位置
    document.getElementById('dispatchForm').scrollIntoView({ behavior: 'smooth' });
}

// 处理分发表单提交
async function handleDispatchSubmit(event) {
    event.preventDefault();
    console.log('📤 处理模型分发提交');
    
    const formData = new FormData(event.target);
    
    // 获取选中的客户端
    const selectedClients = Array.from(document.querySelectorAll('#dispatchTargetClients input[type="checkbox"]:checked'))
        .map(checkbox => checkbox.value);
    
    const dispatchData = {
        model_name: formData.get('model_name'),
        model_url: formData.get('model_url'),
        model_type: formData.get('model_type'),
        version: formData.get('version'),
        description: formData.get('description'),
        author: formData.get('author'),
        target_clients: selectedClients
    };
    
    try {
        showNotification('开始分发模型...', 'info');
        
        const response = await fetch(`${API_BASE}/dispatch`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(dispatchData)
        });
        
        if (!response.ok) {
            const errorData = await response.json();
            throw new Error(errorData.detail || '分发请求失败');
        }
        
        const result = await response.json();
        console.log('✅ 模型分发启动成功:', result);
        
        showNotification(`模型分发已启动: ${result.dispatch_id}`, 'success');
        
        // 刷新分发状态
        await loadDispatchStatus();
        
        // 重置表单
        event.target.reset();
        
    } catch (error) {
        console.error('❌ 模型分发失败:', error);
        showNotification('模型分发失败: ' + error.message, 'error');
    }
}

// 加载分发状态
async function loadDispatchStatus() {
    console.log('📊 加载分发状态');
    
    try {
        const response = await fetch(`${API_BASE}/dispatch`);
        if (!response.ok) {
            throw new Error('获取分发状态失败');
        }
        
        const data = await response.json();
        console.log('📊 分发状态数据:', data);
        
        displayDispatchStatus(data.dispatches || []);
        
    } catch (error) {
        console.error('❌ 加载分发状态失败:', error);
        document.getElementById('dispatchStatusList').innerHTML = 
            `<div class="error">加载分发状态失败: ${error.message}</div>`;
    }
}

// 显示分发状态
function displayDispatchStatus(dispatches) {
    const container = document.getElementById('dispatchStatusList');
    
    if (!dispatches || dispatches.length === 0) {
        container.innerHTML = '<div class="empty">暂无分发任务</div>';
        return;
    }
    
    const html = dispatches.map(dispatch => {
        const statusClass = getDispatchStatusClass(dispatch.status);
        const progress = dispatch.progress || 0;
        const startTime = new Date(dispatch.start_time * 1000).toLocaleString('zh-CN');
        const endTime = dispatch.end_time ? new Date(dispatch.end_time * 1000).toLocaleString('zh-CN') : '进行中';
        
        return `
            <div class="dispatch-item">
                <div class="dispatch-header">
                    <h4>${dispatch.model_name}</h4>
                    <span class="status-badge ${statusClass}">${getDispatchStatusLabel(dispatch.status)}</span>
                </div>
                <div class="dispatch-details">
                    <div class="progress-bar">
                        <div class="progress-fill" style="width: ${progress}%"></div>
                        <span class="progress-text">${progress.toFixed(1)}%</span>
                    </div>
                    <div class="dispatch-info">
                        <div class="info-item">
                            <strong>分发ID:</strong> ${dispatch.dispatch_id}
                        </div>
                        <div class="info-item">
                            <strong>目标客户端:</strong> ${dispatch.target_clients.length} 个
                        </div>
                        <div class="info-item">
                            <strong>已完成:</strong> ${dispatch.completed_clients.length} 个
                        </div>
                        <div class="info-item">
                            <strong>失败:</strong> ${dispatch.failed_clients.length} 个
                        </div>
                        <div class="info-item">
                            <strong>开始时间:</strong> ${startTime}
                        </div>
                        <div class="info-item">
                            <strong>结束时间:</strong> ${endTime}
                        </div>
                        ${dispatch.error_message ? `<div class="error-message">错误: ${dispatch.error_message}</div>` : ''}
                    </div>
                </div>
            </div>
        `;
    }).join('');
    
    container.innerHTML = html;
}

// 获取分发状态样式类
function getDispatchStatusClass(status) {
    const statusClasses = {
        'pending': 'status-pending',
        'downloading': 'status-downloading',
        'completed': 'status-success',
        'completed_with_errors': 'status-warning',
        'failed': 'status-error',
        'cancelled': 'status-cancelled'
    };
    return statusClasses[status] || 'status-unknown';
}

// 获取分发状态标签
function getDispatchStatusLabel(status) {
    const statusLabels = {
        'pending': '等待中',
        'downloading': '下载中',
        'completed': '已完成',
        'completed_with_errors': '部分失败',
        'failed': '失败',
        'cancelled': '已取消'
    };
    return statusLabels[status] || status;
}

// 加载可用客户端
async function loadAvailableClients() {
    console.log('📱 加载可用客户端');

    try {
        const response = await fetch(`${API_BASE}/clients/available`);
        if (!response.ok) {
            throw new Error(`HTTP ${response.status}: ${response.statusText}`);
        }

        const data = await response.json();
        console.log('📱 可用客户端数据:', data);

        if (data.success) {
            const clients = data.clients || [];
            console.log(`📱 找到 ${clients.length} 个可用客户端`);

            displayAvailableClients(clients);
            updateClientSelectOptions(clients);

            if (clients.length === 0) {
                console.warn('⚠️ 没有找到可用的客户端');
            }
        } else {
            throw new Error(data.error || '获取客户端数据失败');
        }

    } catch (error) {
        console.error('❌ 加载可用客户端失败:', error);
        const availableClientsList = document.getElementById('availableClientsList');
        const dispatchTargetClients = document.getElementById('dispatchTargetClients');

        if (availableClientsList) {
            availableClientsList.innerHTML =
                `<div class="error">加载可用客户端失败: ${error.message}</div>`;
        }

        if (dispatchTargetClients) {
            dispatchTargetClients.innerHTML =
                `<div class="error">无法加载客户端列表: ${error.message}</div>`;
        }
    }
}

// 显示可用客户端
function displayAvailableClients(clients) {
    const container = document.getElementById('availableClientsList');

    if (!clients || clients.length === 0) {
        container.innerHTML = '<div class="empty">暂无可用客户端</div>';
        return;
    }

    const html = `
        <div class="table-container">
            <table class="data-table">
                <thead>
                    <tr>
                        <th>客户端名称</th>
                        <th>客户端ID</th>
                        <th>主机名</th>
                        <th>IP地址</th>
                        <th>能力</th>
                        <th>状态</th>
                    </tr>
                </thead>
                <tbody>
                    ${clients.map(client => `
                        <tr>
                            <td>${client.name || client.client_id}</td>
                            <td><code>${client.client_id}</code></td>
                            <td>${client.hostname}</td>
                            <td>${client.ip_address}:${client.port}</td>
                            <td>${client.capabilities.join(', ')}</td>
                            <td><span class="status-badge status-online">在线</span></td>
                        </tr>
                    `).join('')}
                </tbody>
            </table>
        </div>
    `;

    container.innerHTML = html;
}

// 更新客户端选择选项
function updateClientSelectOptions(clients) {
    const container = document.getElementById('dispatchTargetClients');
    if (!container) return;
    
    if (!clients || clients.length === 0) {
        container.innerHTML = '<div class="empty">暂无可用客户端</div>';
        return;
    }
    
    // 生成客户端选择列表
    const html = clients.map(client => `
        <div class="client-selection-item">
            <input type="checkbox" id="client_${client.client_id}" value="${client.client_id}" checked>
            <label for="client_${client.client_id}">
                <div class="client-info">
                    <div class="client-name">${client.name || client.client_id}</div>
                    <div class="client-details">${client.hostname} • ${client.ip_address}</div>
                </div>
                <div class="client-status ${client.status === 'online' ? 'online' : 'offline'}">
                    ${client.status === 'online' ? '在线' : '离线'}
                </div>
            </label>
        </div>
    `).join('');
    
    container.innerHTML = html;
    
    // 绑定全选/取消全选功能
    bindSelectAllFunctionality();
}

// 绑定全选/取消全选功能
function bindSelectAllFunctionality() {
    const selectAllCheckbox = document.getElementById('selectAllClients');
    const clientCheckboxes = document.querySelectorAll('#dispatchTargetClients input[type="checkbox"]');

    if (!selectAllCheckbox) {
        console.warn('未找到全选复选框');
        return;
    }

    // 移除之前的事件监听器（避免重复绑定）
    selectAllCheckbox.removeEventListener('change', handleSelectAllChange);

    // 全选复选框变化时
    function handleSelectAllChange() {
        const currentCheckboxes = document.querySelectorAll('#dispatchTargetClients input[type="checkbox"]');
        currentCheckboxes.forEach(checkbox => {
            checkbox.checked = selectAllCheckbox.checked;
        });
    }

    selectAllCheckbox.addEventListener('change', handleSelectAllChange);

    // 单个客户端复选框变化时
    clientCheckboxes.forEach(checkbox => {
        checkbox.addEventListener('change', function() {
            const checkedCount = Array.from(clientCheckboxes).filter(cb => cb.checked).length;
            const totalCount = clientCheckboxes.length;
            
            if (checkedCount === totalCount) {
                selectAllCheckbox.checked = true;
                selectAllCheckbox.indeterminate = false;
            } else if (checkedCount === 0) {
                selectAllCheckbox.checked = false;
                selectAllCheckbox.indeterminate = false;
            } else {
                selectAllCheckbox.checked = false;
                selectAllCheckbox.indeterminate = true;
            }
        });
    });
}

// 工具函数
function getStatusLabel(status) {
    const labels = {
        'active': '运行中',
        'loaded': '已加载',
        'unloaded': '未加载',
        'error': '错误'
    };
    return labels[status] || status;
}

function getTypeLabel(type) {
    const labels = {
        'detection': '目标检测',
        'segmentation': '实例分割',
        'classification': '图像分类',
        'pose': '姿态估计'
    };
    return labels[type] || type;
}

function formatFileSize(bytes) {
    if (bytes === 0) return '0 B';
    const k = 1024;
    const sizes = ['B', 'KB', 'MB', 'GB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
}

function downloadCSV(content, filename) {
    const blob = new Blob([content], { type: 'text/csv;charset=utf-8;' });
    const link = document.createElement('a');
    const url = URL.createObjectURL(blob);
    link.setAttribute('href', url);
    link.setAttribute('download', filename);
    link.style.visibility = 'hidden';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
}
